/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.validation;

import static org.metalframework.util.AnnotationUtils.*;

import java.util.*;

import javax.annotation.*;
import javax.validation.*;

import org.aopalliance.intercept.*;
import org.metalframework.annotation.*;
import org.metalframework.exception.*;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;

@InfrastructureComponent(ValidateInterceptor.NAME)
public class ValidateInterceptor implements MethodInterceptor {

	public static final String NAME = "validateInterceptor";
	
	private static final Logger logger = LoggerFactory.getLogger(ValidateInterceptor.class);
	
	private ConstraintViolationHandler violationHandler;
	private Validator validator;

	public Object invoke(MethodInvocation invocation) throws Throwable {
		logger.debug("Validating parameters of invocation [{}]", invocation);
		
		Object[] arguments = invocation.getArguments();
		List<Validate> annotations = getParameterAnnotations(invocation.getMethod(), Validate.class);
		
		Set<ConstraintViolation<Object>> violations = new HashSet<ConstraintViolation<Object>>();
		for (int i = 0; i < arguments.length; i++) {
			if (arguments[i] != null && annotations.get(i) != null) {
				violations.addAll(validateArgument(arguments[i], annotations.get(i).value()));
			}
		}
		
		if (!violations.isEmpty()) {
			getViolationHandler().handle(violations);
			throw new DomainValidationException(violations);
		}
		
		return invocation.proceed();
	}
	
	protected Set<ConstraintViolation<Object>> validateArgument(Object argument, Class<?>[] groups) {
		return getValidator().validate(argument, groups);
	}

	// Getters/Setters
	
	public ConstraintViolationHandler getViolationHandler() {
		return violationHandler;
	}
	
	@Required @Resource
	public void setViolationHandler(ConstraintViolationHandler violationHandler) {
		this.violationHandler = violationHandler;
	}
	
	public Validator getValidator() {
		return validator;
	}
	
	@Required @Resource
	public void setValidator(Validator validator) {
		this.validator = validator;
	}
}
